<?php

class MemberController extends Zend_Controller_Action {

	//Mang tham so nhan duoc o moi Action
	protected $_arrParam;

	//Duong dan cua Controller
	protected $_currentController;

	//Duong dan cua Action chinh
	protected $_actionMain;

	//Thong so phan trang
	protected $_paginator = array('itemCountPerPage' => 5, 'pageRange' => 3);
	protected $_namespace;

	//User đang login
	protected $_crrUsra;

	protected $_controllerConfig;

	public function init() {

		$file_uri = $this->view->baseUrl(DEFAULT_PATH . '/css/style_profile.css');
		$this->view->headLink()->appendStylesheet($file_uri);

		// Meta
		$this->view->headMeta()->setName('description', 'Trang web chuyên về thông tin phòng trọ.');
		$this->view->headMeta()->appendName('keywords', 'phòng trọ, phòng cho thuê, thuê phòng, nhà trọ');

		//Mang tham so nhan duoc o moi Action
		$this->_arrParam = $this->_request->getParams();

		//Duong dan cua Controller
		$this->_currentController = '/' . $this->_arrParam['controller'];

		//Duong dan cua Action chinh
		$this->_actionMain = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];

		$this->_paginator['currentPage'] = $this->_request->getParam('page', 1);
		$this->_arrParam['paginator'] = $this->_paginator;

		//Luu cac du lieu filter vao SESSION
		//Dat ten SESSION
		$this->_namespace = $this->_arrParam['module'] . '-' . $this->_arrParam['controller'];
		$ssFilter = new Zend_Session_Namespace($this->_namespace);
		if(empty($ssFilter->col)) {
			$ssFilter->keywords 	= '';
			$ssFilter->col 			= 'id';
			$ssFilter->order 		= 'DESC';
		}

		// Lấy thông tin của user đăng nhập đã lưu trong session
		$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('user'));
		if ($this->_arrParam['action'] != 'register' && $this->_arrParam['action'] != 'signin' && $this->_arrParam['action'] != 'signout'
		&& $this->_arrParam['action'] != 'uploadify' && $this->_arrParam['action'] != 'uploadavatar' && $this->_arrParam['action'] != 'signinvalidate'
		&& $this->_arrParam['action'] != 'refresh' && $this->_arrParam['action'] != 'activeaccount' && $this->_arrParam['action'] != 'forgotpass'
		&& $this->_arrParam['action'] != 'confirm' && $this->_arrParam['action'] != 'filter') {
			if($auth->hasIdentity()){
				$this->_crrUsra = $auth->getIdentity();
				if ($ssFilter->actionname != $this->_arrParam['action']) {
					$ssFilter->keywords 	= '';
					$ssFilter->col 			= 'id';
					$ssFilter->order 		= 'DESC';
				}
				$ssFilter->actionname 	= $this->_arrParam['action'];
			} else {
				$message = new Zend_Session_Namespace('message');
				$message->msg = '<ul class="messages"><li class="success">Hãy đăng nhập trước khi thực hiện thao tác này.</li></ul>';
				$message->redirect = '<script type="text/javascript">
								        var settimmer = 0;
								        $(function(){
								                window.setInterval(function() {
								                    var timeCounter = $("b[id=show-time]").html();
								                    var updateTime = eval(timeCounter)- eval(1);
								                    $("b[id=show-time]").html(updateTime);
								
								                    if(updateTime == 0){
								                        window.location = ("' . $this->view->baseUrl('') .'");
								                    }
								                }, 1000);
								
								        });
								    </script>';
				$message->redirect .= '<div class="redirect-msg"><div id="my-timer">Trang sẽ tự chuyển sau <b id="show-time">5</b> giây.</div><br />';
				$message->redirect .= '<p>Nếu không muốn đợt lâu vui lòng click vào <a href="' . $this->view->baseUrl('') .'">đây</a>.</p></div>';
				$this->_redirect('/message');
			}
		}

		$this->_arrParam['ssFilter']['keywords'] 	= $ssFilter->keywords;
		$this->_arrParam['ssFilter']['col'] 		= $ssFilter->col;
		$this->_arrParam['ssFilter']['order'] 		= $ssFilter->order;

		//Truyen ra view
		$this->view->arrParam = $this->_arrParam;
		$this->view->currentController = $this->_currentController;
		$this->view->actionMain = $this->_actionMain;

		// Menu loại tin
		$model = new Default_Model_LoaiTinMapper();
		$this->view->menuLoaiTin = $model->fetchAll('da_xoa = 0');

		//khai bao thu muc upload
		$this->_controllerConfig  = array('imagesDir' => PUBLIC_IMG_PATH . '/');
		$this->_arrParam['controllerConfig'] = $this->_controllerConfig;
	}

	// Validation Đăng nhập
	public function signinvalidateAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new Default_Form_Login();
		$form->isValid($this->_getAllParams());
		$json = $form->getMessages();
		header('Content-type: application/json');
		echo Zend_Json::encode($json);
	}

	// Đăng nhập
	public function signinAction() {
		$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('user'));
		if ($auth->hasIdentity()) {
			$auth->clearIdentity();
		}

		if ($this->_request->isPost()) {
			$message = '';
			$flag = false;
			//1.Goi ket noi voi Zend Db
			$db = Zend_Registry::get('connectDB');
			//2. Khoi tao Zend Autho
			$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('user'));

			//3. Lay gia tri duoc gui qua tu FORM
			$username = $this->_arrParam['login_username'];
			$password = Zendhlt_Encode::password($this->_arrParam['login_password']);

			$validator = new Zend_Validate_EmailAddress();
			if ($validator->isValid($username)) {
				$identityField = 'email';
			} else {
				$identityField = 'username';
			}

			//4. Khai bao bang va 2 cot se su dung so sanh trong qua trinh login
			$authAdapter = new Zend_Auth_Adapter_DbTable($db);
			$authAdapter->setTableName('tb_users')
						->setIdentityColumn($identityField)
						->setCredentialColumn('password');

			$model = new Default_Model_UsersMapper();
			$user = $model->CheckActivekey($username);
			if($user != null) {
				//5. Dua vao so sanh voi du lieu khai bao o muc 3
				$authAdapter->setIdentity($username);
				$authAdapter->setCredential($password);

				//6. Kiem tra trang thai cua user neu IDGROUP > 2 moi duoc login
				$select = $authAdapter->getDbSelect();

				//7. Lay ket qua truy van
				$result = $auth->authenticate($authAdapter);
				if ($result->isValid()) {
					//8. Lay nhung du lieu can thiet trong bang users neu login thanh cong
					$data = $authAdapter->getResultRowObject(array('id', 'username', 'ho_ten', 'email', 'dien_thoai'), array('password'));

					//9. Luu nhung du lieu cua member vao session
					$auth->getStorage()->write($data);
					$flag = true;
				}

				if ($flag == true) {
					$infoUser = $auth->getIdentity();
					if (!isset($this->_arrParam['format'])) {
						$uri = str_replace('/member/signin', '', $_SERVER['REQUEST_URI']);
						if (strlen($uri) > 0)
							$this->_redirect($uri);
						else
							$this->_redirect('');
					}
				} else {
					$message = 'Nhập sai mật khẩu!';
				}
			} else {
				$message = 'Tài khoản không tồn tại hoặc chưa được kích hoạt!';
			}

			if (isset($this->_arrParam['format'])) {
				if ($this->_arrParam['format'] = "json") {
					if ($auth->hasIdentity()) {
						$json = array('login' => $flag, 'message' => $message, "user" => $auth->getStorage()->read()->username);
						//Remember function
						$remember = isset($this->_arrParam['login_remember']) && is_array($this->_arrParam['login_remember']);
						$seconds  = 60 * 60 * 24 * 2; //2 days
						if ($remember) {
							Zend_Session::RememberMe($seconds);
						} else {
							Zend_Session::ForgetMe();
						}
						$session = new Zend_Session_Namespace('identity');
						$session->username = $data->username;
						$session->email = $data->email;
					} else {
						$json = array('login' => $flag, 'message' => $message, "user" => "");
					}
					$this->_helper->layout()->disableLayout();
					$this->_helper->viewRenderer->setNoRender();
					echo json_encode($json);
				}
			}
		}
	}

	// Đăng xuất
	public function signoutAction() {
		$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('user'));
		$auth->clearIdentity();
		$this->_redirect('');
	}

	// Đăng ký
	public function registerAction() {
		$this->_helper->layout()->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		if($this->_arrParam['action_type'] == "validate") {
			$form = new Default_Form_RegisterUser();
			$form->isValid($this->_getAllParams());
			$json = $form->getMessages();
			header('Content-type: application/json');
			echo Zend_Json::encode($json);
		
		} else {
			$message = "";
			$flag = false;
			
			try {
				if ($this->getRequest()->isPost()) {
					$form = new Default_Form_RegisterUser();
					$formData = $this->getRequest()->getPost();
					
					if ($form->isValid($formData)) {
						$model = new Default_Model_UsersMapper();
						$user = new Default_Model_TableColumn_Users($formData);
						$user->setId(0);
						$user->setPassword(Zendhlt_Encode::password($user->getPassword()));
						$activeCode = Zendhlt_Encode::password($user->getUsername().$user->getEmail());
						$user->setMa_kich_hoat($activeCode);
						
						$transport = Zend_Registry::get('mailTransport');
						$m = new Zendhlt_Mail_Mail();
						$m	->setSubject("[Kênh nhà trọ] Kích hoạt tài khoản của bạn tại website Kênh nhà trọ")
							->addTo($user->getEmail())
							->setViewParam('username', $user->getUsername())
							->setViewParam('hoten', $user->getHo_ten())
							->setViewParam('linkactive', '/member/activeaccount/code/' . $activeCode)
							->sendHtmlTemplate("register.tpl", "UTF-8", $transport);
						
						$model->save($user);
						$message = 'Đăng ký thành công. Vui lòng kiểm tra email để hoàn tất đăng ký. ';
						$flag = true;
					
					} else {
						$message = 'Vui lòng nhập đúng thông tin đăng ký!';
					}
				}
			
			} catch (Exception $e) {
				$message = 'Đăng ký thất bại';
			}
			
			$json = array('register' => $flag, 'message' => $message);
			echo json_encode($json);
		}
	}
	
	// Confirm link forgot password
	public function confirmAction() {
		// Title
		$this->view->headTitle('Quên mật khẩu');
		
		$check = false;
		$title = 'Xác nhận liên kết';
		
		$form = new Default_Form_ChangePassword();
		$form->removeElement('oldpassword');
		
		$model = new Default_Model_UsersMapper();
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if (isset($formData['reset'])) {
				$this->redirect('');
			} else {
				if ($form->isValid($formData)) {
					$data = array('password' => Zendhlt_Encode::password($formData['newpassword']), 'ma_forgot_pass' => true);
					$model->change(0, $data, "ma_forgot_pass = '" . $this->_arrParam['code'] . "'");
					
					$msg = '<ul class="messages"><li class="success">Chúc mừng bạn đã lấy lại được mật khẩu.</li></ul>';
					$redirect = '<script type="text/javascript">
							        var settimmer = 0;
							        $(function(){
							                window.setInterval(function() {
							                    var timeCounter = $("b[id=show-time]").html();
							                    var updateTime = eval(timeCounter)- eval(1);
							                    $("b[id=show-time]").html(updateTime);
							
							                    if(updateTime == 0){
							                        window.location = ("' . $this->view->baseUrl('') .'");
							                    }
							                }, 1000);
							
							        });
							    </script>';
					$redirect .= '<div class="redirect-msg"><div id="my-timer">Trang sẽ tự chuyển sau <b id="show-time">5</b> giây.</div><br />';
					$redirect .= '<p>Nếu không muốn đợt lâu vui lòng click vào <a href="' . $this->view->baseUrl('') .'">đây</a>.</p></div>';
					$this->view->msg = $msg;
					$this->view->redirect = $redirect;
					$this->renderScript('message/index.phtml');
				} else {
					$check = true;
					$this->view->form_forgot_pass = $form;
					$form->populate($formData);
				}
			}
		} else {
			if (isset($this->_arrParam['code'])) {
				$date_format = Default_Model_TableColumn_Users::DATE_FORMAT_FULL_EN;
				$now = date($date_format, time());
				$user = $model->fetch("ma_forgot_pass = '" . $this->_arrParam['code'] . "' and ngay_forgot_pass >= '" . $now . "'");
				
				if (!empty($user)) {
					$title = 'Quên mật khẩu';
					$this->view->form_forgot_pass = $form;
					
					$check = true;
				}
			}
		}

		if (!$check) {
			$message = '<ul>';
			$message .= '<li>Link xác nhận không chính xác</li>';
			$message .= '<li>Hoặc link đã hết hạn hoặc đã được xác nhận.</li>';
			$message .= '</ul>';
			$this->view->message = $message;
		}
		$this->view->title = $title;
		$this->view->check = $check;
	}
	
	// Forgot password
	public function forgotpassAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();
		
		$form = new Default_Form_RegisterUser();
		$form->removeElement('username');
		$form->removeElement('password');
		$form->removeElement('cfrmpassword');
		$form->removeElement('ho_ten');
		$form->getElement('email')->removeValidator('Db_NoRecordExists');
		$flag = false;
		
		if($this->_arrParam['action_type'] == "validate") {
			$form->isValid($this->_getAllParams());
			$json = $form->getMessages();
			header('Content-type: application/json');
			echo Zend_Json::encode($json);
		} else {
			try {
				if ($this->getRequest()->isPost()) {
					$formData = $this->getRequest()->getPost();
					if ($form->isValid($formData)) {
						$model = new Default_Model_UsersMapper();
						$user = $model->fetch("email = '" . $this->_arrParam['email'] . "'");
						if (!empty($user)) {
							$keyForgot = Zendhlt_Encode::genRandomString(30);
							$date_format = Default_Model_TableColumn_Users::DATE_FORMAT_FULL_EN;
							$now = time() + 168 * 3600;
							$ngay_het_han = date($date_format, $now);
							$data = array('ma_forgot_pass' => $keyForgot, 'ngay_forgot_pass' => $ngay_het_han);
							
							$transport = Zend_Registry::get('mailTransport');
							$m = new Zendhlt_Mail_Mail();
							$m	->setSubject("[Kênh nhà trọ] Cấp lại mật khẩu của bạn tại website Kênh nhà trọ")
								->addTo($this->_arrParam['email'])
								->setViewParam('hoten', $user->getHo_ten())
								->setViewParam('linkforgot', '/member/confirm/code/' . $keyForgot)
								->setViewParam('ngayhethan', date('d/m/Y', $now))
								->sendHtmlTemplate("forgotpass.tpl", "UTF-8", $transport);
							
							$model->change(0, $data, "email = '" . $this->_arrParam['email'] . "'");
							$flag = true;
							$message = 'Hệ thống đã gửi email cho bạn qua hộp thư đã đăng ký với Kênh nhà trọ.<br />';
							$message .= 'Vui lòng làm theo hướng dẫn trong email để lấy lại mật khẩu.';
						} else {
							$message = 'Email không tồn tại.';
						}
					}
				}
			} catch (Exception $e) {
				$message = 'Quá trình khôi phục mật khẩu không thành công.';
			}
			
			$json = array('result' => $flag, 'message' => $message);
			echo json_encode($json);
		}
	}
	
	// Active account
	public function activeaccountAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();
		$activeCode = $this->_arrParam['code'];
		$model = new Default_Model_UsersMapper();
		$user = $model->activeUserAccount($activeCode);
		
		$message = new Zend_Session_Namespace('message');
		$message->msg = '<ul class="messages"><li class="success">Tài khoản đã kích hoạt thành công.</li></ul>';
		$message->redirect = '<script type="text/javascript">
						        var settimmer = 0;
						        $(function(){
						                window.setInterval(function() {
						                    var timeCounter = $("b[id=show-time]").html();
						                    var updateTime = eval(timeCounter)- eval(1);
						                    $("b[id=show-time]").html(updateTime);
						
						                    if(updateTime == 0){
						                        window.location = ("' . $this->view->baseUrl('') .'");
						                    }
						                }, 1000);
						
						        });
						    </script>';
		$message->redirect .= '<div class="redirect-msg"><div id="my-timer">Trang sẽ tự chuyển sau <b id="show-time">5</b> giây.</div><br />';
		$message->redirect .= '<p>Nếu không muốn đợt lâu vui lòng click vào <a href="' . $this->view->baseUrl('') .'">đây</a>.</p></div>';
		$this->_redirect('/message');
	}
	
	// Profile user
	public function profileAction() {
		// Title
		$this->view->headTitle('Thông tin cá nhân');

		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );


		$model = new Default_Model_UsersMapper();

		$form = new Default_Form_User();
		$form->submit->setLabel('Chỉnh sửa');
		$form->reset->setLabel('Hủy');
		
		//Remove các trường không được phép sửa;
		$form->removeElement('username');
		$form->removeElement('password');
		$form->removeElement('email');
		
		$this->view->frmUser = $form;

		// Selectbox thành phố
		$model = new Default_Model_ThanhPhoMapper();
		$arrOptions = $model->fetchAll();
		$key = '';
		$value = ' -- Thành phố -- ';
		$form->thanh_pho->addMultiOption($key, $value);
		foreach($arrOptions as $val) {
			$key   = $val->id;
			$value = $val->ten;
			$form->thanh_pho->addMultiOption($key, $value);
		}
		$form->ngay_sinh->setAttribs(array('readonly' => 'readonly'));

		$formChangePass = new Default_Form_ChangePassword();
		
		$this->view->frmChangePass = $formChangePass;

		$model = new Default_Model_UsersMapper();
		$profile = $model->fetch('id = ' . $this->_crrUsra->id);
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			$flag = false;
			if ($form->isValid($formData)) {
				$user = new Default_Model_TableColumn_Users($formData);
				$user->setId($this->_crrUsra->id);
				$avatar = $profile->hinh_anh;
				if ($formData['hidden_hinh_anh'] != $avatar) {
					$uploadDir 	= $this->_controllerConfig['imagesDir'];
					$source = 'public/resources/tmp/thumb_images_64x64/';
					$destination = 'public/resources/user/user/avatars/';
					@unlink($uploadDir . '/user/user/avatars/' . $avatar);
					$avatar = $formData['hidden_hinh_anh'];
					copy($source . $avatar, $destination . $avatar);
					@unlink($uploadDir . '/tmp/full_images/' . $avatar);
					@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
				}
				$user->setHinh_anh($avatar);
				$model->save($user);
				$flag = true;
			}
			$this->_helper->viewRenderer->setNoRender();
			$this->_helper->getHelper('layout')->disableLayout();
			header('Content-type: application/json');
			$json = array('edit' => $flag);
			echo json_encode($json);
		} else {
			$this->view->profile = $profile;
			$form->populate($profile->toArray());
		}
	}
	
	// Thay đổi password
	public function changepasswordAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();
		
		$form = new Default_Form_ChangePassword();
		
		$model = new Default_Model_UsersMapper();
		$flag = false;
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)) {
				$user = $model->fetch("username = '" . $this->_crrUsra->username . "' AND password = '" . Zendhlt_Encode::password($formData['oldpassword']) . "'");
				if (!empty($user)) {
					$data = array('password' => Zendhlt_Encode::password($formData['newpassword']));
					$model->change($this->_crrUsra->id, $data);
					$flag = true;
					$message = '';
				} else {
					$message = 'Mật khẩu không chính xác';
				}
			}
		}
		$json = array('edit' => $flag, 'message' => $message);
		echo json_encode($json);
	}

	// Đăng tin phòng trọ
	public function dangtinnhatroAction() {
			
		// Title
		$this->view->headTitle('Đăng tin nhà trọ');
	
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );
		
		$model = new Default_Model_PtrTinRaoMapper();
		// Đếm số item trong Ptr_Tin_Rao
		$totalItem = $model->countItem(null, 'nguoi_dang = ' . $this->_crrUsra->id . ' AND trang_thai <> 2');
		if ($totalItem > 5) {
			$this->view->check = false;
			$message = '<ul>';
			$message .= '<li>Số lượng tin đăng đã vượt quá giới hạn cho phép là 5.</li>';
			$message .= '<li>Để có thể đăng tin hãy xóa tin cũ.</li>';
			$message .= '</ul>';
			$this->view->message = $message;
		} else {
			$this->view->check = true;
	
			$this->view->bodyScripts = 'onload="initialize()"';
	
			//maps google
			$this->view->headScript()->appendFile('https://maps.googleapis.com/maps/api/js?key=AIzaSyDypXt_xTgAMOTpSEdwmPXjUA0JGGbyXhY&sensor=false');
			$file_uri = $this->view->baseUrl(PUBLIC_PATH . '/js/google.map.js');
			$this->view->headScript()->appendFile($file_uri);
	
			$form = new Default_Form_PtrTinRao();
			$form->submit->setLabel('Thêm mới');
			$form->reset->setLabel('Hủy');
			$this->view->frmPtrTinRao = $form;
	
			// Selectbox thành phố
			$model = new Default_Model_ThanhPhoMapper();
			$arrOptions = $model->fetchAll();
			$key = '';
			$value = ' -- Thành phố -- ';
			$form->thanh_pho->addMultiOption($key, $value);
			foreach($arrOptions as $val) {
				$key   = $val->id;
				$value = $val->ten;
				$form->thanh_pho->addMultiOption($key, $value);
			}
			$form->thanh_pho->setAttrib('onchange', 'getDistrict(false, thanh_pho, quan_huyen)');
			$form->quan_huyen->setAttrib('onchange', 'placeChange()');
	
			// Selectbox loại phòng
			$model = new Default_Model_LoaiPhongMapper();
			$arrOptions = $model->fetchAll('da_xoa = 0');
			$key = '';
			$value = ' -- Loại phòng -- ';
			foreach($arrOptions as $val) {
				$form->loai_phong->addMultiOption($key, $value);
				$key   = $val->id;
				$value = $val->ten;
			}
			$form->loai_phong->addMultiOption($key, $value);
	
			// Selectbox loại tin
			$model = new Default_Model_LoaiTinMapper();
			$arrOptions = $model->fetchAll('da_xoa = 0 AND group_loai_tin = 0');
			$key = '';
			$value = ' -- Loại tin -- ';
			foreach($arrOptions as $val) {
				$form->loai_tin->addMultiOption($key, $value);
				$key   = $val->id;
				$value = $val->ten;
			}
			$form->loai_tin->addMultiOption($key, $value);
			$form->nguoi_lien_he->setValue($this->_crrUsra->ho_ten);
			$form->so_dien_thoai->setValue($this->_crrUsra->dien_thoai);
	
			if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();
				if (isset($formData['reset'])) {
					$avatar = $formData['hidden_avatar'];
					$uploadDir 	= $this->_controllerConfig['imagesDir'];
					if (file_exists($uploadDir . '/tmp/full_images/' . $avatar)) {
						@unlink($uploadDir . '/tmp/full_images/' . $avatar);
						@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
					}
					$this->_redirect('/member/ptrtinrao');
				} elseif ($form->isValid($formData)) {
					$model = new Default_Model_PtrTinRaoMapper();
					$ptrtinrao = new Default_Model_TableColumn_PtrTinRao($formData);
					$ptrtinrao->setId(0);
					$ptrtinrao->setNguoi_dang($this->_crrUsra->id);
					$ptrtinrao->setGoi_tin(4);
					$avatar = $formData['hidden_avatar'];
					if ($avatar == "")
					$avatar = 'avatar_home.png';
					else {
						$source = 'public/resources/tmp/thumb_images_64x64/';
						$destination = 'public/resources/phong_tro/avatar/';
						copy($source . $avatar, $destination . $avatar);
						$uploadDir 	= $this->_controllerConfig['imagesDir'];
						@unlink($uploadDir . '/tmp/full_images/' . $avatar);
						@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
					}
					$listImg = $avatar;
					if (!empty($formData['listImage'])) {
						$listImg .= ',' . $formData['listImage'];
						$listImage = explode (',', $formData['listImage']);
						foreach ($listImage as $filename) {
							$source = 'public/resources/tmp/';
							$destination = 'public/resources/phong_tro/album/';
							copy($source . 'thumb_images_428x320/' . $filename, $destination . 'thumb_images_428x320/' . $filename);
							copy($source . 'thumb_images_90x70/' . $filename, $destination . 'thumb_images_90x70/' . $filename);
							$uploadDir 	= $this->_controllerConfig['imagesDir'];
							@unlink($uploadDir . '/tmp/full_images/' . $filename);
							@unlink($uploadDir . '/tmp/thumb_images_428x320/' . $filename);
							@unlink($uploadDir . '/tmp/thumb_images_90x70/' . $filename);
						}
					}
					$ptrtinrao->setHinh_anh($listImg);
					$model->save($ptrtinrao);
					
					$msg = '<ul class="messages"><li class="success">Bạn đã đăng tin thành công và đang chờ duyệt.</li></ul>';
					$redirect = '<script type="text/javascript">
									        var settimmer = 0;
									        $(function(){
									                window.setInterval(function() {
									                    var timeCounter = $("b[id=show-time]").html();
									                    var updateTime = eval(timeCounter)- eval(1);
									                    $("b[id=show-time]").html(updateTime);
									
									                    if(updateTime == 0){
									                        window.location = ("' . $this->view->baseUrl('/member/ptrtinrao/loaitin/' . $formData['loai_tin']) .'");
									                    }
									                }, 1000);
									
									        });
									    </script>';
					$redirect .= '<div class="redirect-msg"><div id="my-timer">Trang sẽ tự chuyển sau <b id="show-time">5</b> giây.</div><br />';
					$redirect .= '<p>Nếu không muốn đợt lâu vui lòng click vào <a href="' . $this->view->baseUrl('/member/ptrtinrao/loaitin/' . $formData['loai_tin']) .'">đây</a>.</p></div>';
					$this->view->msg = $msg;
					$this->view->redirect = $redirect;
					$this->renderScript('message/index.phtml');
				} else {
					$modelDistricts = new Default_Model_QuanHuyenMapper();
					$arrOptions = $modelDistricts->fetchAll('thanhpho = ' . $formData['thanh_pho']);
					$key = '';
					$value = ' -- Quận huyện -- ';
					foreach($arrOptions as $val) {
						$form->quan_huyen->addMultiOption($key, $value);
						$key   = $val->id;
						$value = $val->ten;
					}
					$form->quan_huyen->addMultiOption($key, $value);
					$form->populate($formData);
				}
			}
		}
	}

	// Chỉnh sửa tin phòng trọ
	public function chinhsuatinnhatroAction() {
		// Title
		$this->view->headTitle('Chỉnh sửa tin nhà trọ');
		
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );

		//maps google
		$this->view->headScript()->appendFile('https://maps.googleapis.com/maps/api/js?key=AIzaSyDypXt_xTgAMOTpSEdwmPXjUA0JGGbyXhY&sensor=false');
		$file_uri = $this->view->baseUrl(PUBLIC_PATH . '/js/google.map.js');
		$this->view->headScript()->appendFile($file_uri);

		$form = new Default_Form_PtrTinRao();
		$form->submit->setLabel('Chỉnh sửa');
		$form->reset->setLabel('Hủy');
		$this->view->frmPtrTinRao = $form;

		// Selectbox thành phố
		$model = new Default_Model_ThanhPhoMapper();
		$arrOptions = $model->fetchAll();
		$key = '';
		$value = ' -- Thành phố -- ';
		$form->thanh_pho->addMultiOption($key, $value);
		foreach($arrOptions as $val) {
			$key   = $val->id;
			$value = $val->ten;
			$form->thanh_pho->addMultiOption($key, $value);
		}
		$form->thanh_pho->setAttrib('onchange', 'getDistrict(false, thanh_pho, quan_huyen)');
		$form->quan_huyen->setAttrib('onchange', 'placeChange()');

		// Selectbox loại phòng
		$model = new Default_Model_LoaiPhongMapper();
		$arrOptions = $model->fetchAll('da_xoa = 0');
		$key = '';
		$value = ' -- Loại phòng -- ';
		foreach($arrOptions as $val) {
			$form->loai_phong->addMultiOption($key, $value);
			$key   = $val->id;
			$value = $val->ten;
		}
		$form->loai_phong->addMultiOption($key, $value);

		// Selectbox loại tin
		$model = new Default_Model_LoaiTinMapper();
		$arrOptions = $model->fetchAll('da_xoa = 0 AND group_loai_tin = 0');
		$key = '';
		$value = ' -- Loại tin -- ';
		foreach($arrOptions as $val) {
			$form->loai_tin->addMultiOption($key, $value);
			$key   = $val->id;
			$value = $val->ten;
		}
		$form->loai_tin->addMultiOption($key, $value);
		
		$model = new Default_Model_PtrTinRaoMapper();
		$ptrtinrao = $model->fetch($this->_arrParam, 'id = ' . $this->_arrParam['id']);

		$this->view->bodyScripts = 'onload="displayLocation(\'' . $ptrtinrao->dia_chi . '\', \'' . $ptrtinrao->latitude . '\',\'' . $ptrtinrao->longitude .'\')"';

		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if (isset($formData['reset'])) {
				$avatar = $formData['hidden_avatar'];
				$uploadDir 	= $this->_controllerConfig['imagesDir'];
				if (file_exists($uploadDir . '/tmp/full_images/' . $avatar)) {
					@unlink($uploadDir . '/tmp/full_images/' . $avatar);
					@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
				}
				$this->_redirect('/member/ptrtinrao/loaitin/' . $formData['loai_tin']);
			} elseif ($form->isValid($formData)) {
				$data = new Default_Model_TableColumn_PtrTinRao($formData);
				$data->setId($ptrtinrao->id);
				$avatar = $formData['hidden_avatar'];
				if ($avatar == "")
					$avatar = 'avatar_home.png';
				else {
					$source = 'public/resources/tmp/thumb_images_64x64/';
					$destination = 'public/resources/phong_tro/avatar/';
					copy($source . $avatar, $destination . $avatar);
					if ($avatar != 'avatar_home.png')
						@unlink($uploadDir . '/phong_tro/avatar/' . $avatar);
					$uploadDir 	= $this->_controllerConfig['imagesDir'];
					@unlink($uploadDir . '/tmp/full_images/' . $avatar);
					@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
				}
				$listImg = $avatar;
				if (!empty($formData['listImage'])) {
					$listImg .= ',' . $formData['listImage'];
					$listImage = explode (',', $formData['listImage']);
					foreach ($listImage as $filename) {
						$source = 'public/resources/tmp/';
						$destination = 'public/resources/phong_tro/album/';
						copy($source . 'thumb_images_428x320/' . $filename, $destination . 'thumb_images_428x320/' . $filename);
						copy($source . 'thumb_images_90x70/' . $filename, $destination . 'thumb_images_90x70/' . $filename);
						$uploadDir 	= $this->_controllerConfig['imagesDir'];
						@unlink($uploadDir . '/tmp/full_images/' . $filename);
						@unlink($uploadDir . '/tmp/thumb_images_428x320/' . $filename);
						@unlink($uploadDir . '/tmp/thumb_images_90x70/' . $filename);
					}
				}
				$data->setHinh_anh($listImg);
				$model->save($data);

				$this->_redirect('/member/ptrtinrao/loaitin/' . $formData['loai_tin']);
			} else {
				$modelDistricts = new Default_Model_QuanHuyenMapper();
				$arrOptions = $modelDistricts->fetchAll('thanhpho = ' . $formData['thanh_pho']);
				$key = '';
				$value = ' -- Quận huyện -- ';
				foreach($arrOptions as $val) {
					$form->quan_huyen->addMultiOption($key, $value);
					$key   = $val->id;
					$value = $val->ten;
				}
				$form->quan_huyen->addMultiOption($key, $value);
				$form->populate($formData);
			}
		} else {
			$form->populate($ptrtinrao->toArray());
		}
	}

	// Danh sách tin rao phòng trọ
	public function ptrtinraoAction() {
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );

		$loai_tin = 2;

		if (isset($this->_arrParam['loaitin'])) {
			$loai_tin = $this->_arrParam['loaitin'];
		}

		switch ($loai_tin) {
			case 1:
				$title = "Danh sách tin tìm phòng trọ";
				break;
					
			default:
				$title = "Danh sách tin tìm người ở trọ";
				break;
		}
		// Title
		$this->view->headTitle($title);

		$this->view->loaitin = $loai_tin;
		$this->view->title = $title;

		// Get items tin của table Ptr_Tin_Rao
		$model = new Default_Model_PtrTinRaoMapper();
		$items = $model->fetch($this->_arrParam, 'nguoi_dang = ' . $this->_crrUsra->id . ' AND trang_thai <> 4 AND loai_tin = ' . $loai_tin, 0, array(array('colName' => 'ngay_dang', 'order' => 'DESC')), 'list');

		// Đếm số item trong Ptr_Tin_Rao
		$totalItem = $model->countItem($this->_arrParam, 'nguoi_dang = ' . $this->_crrUsra->id . ' AND trang_thai <> 2 AND loai_tin = ' . $loai_tin);
		$this->view->totalItems = $totalItem;

		$paginator = new Zendhlt_Paginator();
		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);

		$this->view->Items = $items;
		
		$form = new Default_Form_BuyVIP();
		$model = new Default_Model_GoiTinMapper();
		$arrOptions = $model->fetchAll('ten <> "free"', 'list');
		$key = 0;
		$value = ' -- Chọn gói VIP -- ';
		$form->ten_goi->addMultiOption($key, $value);
		foreach($arrOptions as $val) {
			$key   = $val['id'];
			$value = $val['ten'];
			$form->ten_goi->addMultiOption($key, $value);
		}
		$this->view->frmVIP = $form;
	}

	// Đăng tin ở ghép
	public function dangtinoghepAction() {
		// Title
		$this->view->headTitle('Đăng tin ở ghép');

		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );
		
		$model = new Default_Model_OghTinRaoMapper();
		// Đếm số item trong Ptr_Tin_Rao
		$totalItem = $model->countItem(null, 'nguoi_dang = ' . $this->_crrUsra->id . ' AND trang_thai <> 2');
		if ($totalItem > 5) {
			$this->view->check = false;
			$message = '<ul>';
			$message .= '<li>Số lượng tin đăng đã vượt quá giới hạn cho phép là 5.</li>';
			$message .= '<li>Để có thể đăng tin hãy xóa tin cũ.</li>';
			$message .= '</ul>';
			$this->view->message = $message;
		} else {
			$this->view->check = true;

			$form = new Default_Form_OghTinRao();
			$form->submit->setLabel('Thêm mới');
			$form->reset->setLabel('Hủy');
			$this->view->frmOghTinRao = $form;
	
			// Selectbox thành phố
			$model = new Default_Model_ThanhPhoMapper();
			$arrOptions = $model->fetchAll();
			$key = '';
			$value = ' -- Thành phố -- ';
			$form->thanh_pho->addMultiOption($key, $value);
			foreach($arrOptions as $val) {
				$key   = $val->id;
				$value = $val->ten;
				$form->thanh_pho->addMultiOption($key, $value);
			}
			$form->thanh_pho->setAttrib('onchange', 'getDistrict(false, thanh_pho, quan_huyen)');
	
			// Selectbox loại phòng
			$model = new Default_Model_LoaiPhongMapper();
			$arrOptions = $model->fetchAll('da_xoa = 0');
			$key = '';
			$value = ' -- Loại phòng -- ';
			$form->loai_phong->addMultiOption($key, $value);
			foreach($arrOptions as $val) {
				$key   = $val->id;
				$value = $val->ten;
				$form->loai_phong->addMultiOption($key, $value);
			}
	
			// Selectbox loại tin
			$model = new Default_Model_LoaiTinMapper();
			$arrOptions = $model->fetchAll('da_xoa = 0 AND group_loai_tin = 1');
			$key = '';
			$value = ' -- Loại tin -- ';
			foreach($arrOptions as $val) {
				$form->loai_tin->addMultiOption($key, $value);
				$key   = $val->id;
				$value = $val->ten;
			}
			$form->loai_tin->addMultiOption($key, $value);
			$form->nguoi_lien_he->setValue($this->_crrUsra->ho_ten);
			$form->so_dien_thoai->setValue($this->_crrUsra->dien_thoai);
	
			if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();
				if (isset($formData['reset'])) {
					$this->_redirect('/member/oghtinrao');
				} elseif ($form->isValid($formData)) {
					$model = new Default_Model_OghTinRaoMapper();
					$oghtinrao = new Default_Model_TableColumn_OghTinRao($formData);
					$oghtinrao->setId(0);
					$oghtinrao->setNguoi_dang($this->_crrUsra->id);
					$oghtinrao->setGoi_tin(4);
					$avatar = $formData['hidden_hinh_anh'];
					if ($avatar == "")
					$avatar = 'avatar_home.png';
					else {
						$source = 'public/resources/tmp/thumb_images_64x64/';
						$destination = 'public/resources/phong_tro/avatar/';
						copy($source . $avatar, $destination . $avatar);
						$uploadDir 	= $this->_controllerConfig['imagesDir'];
						@unlink($uploadDir . '/tmp/full_images/' . $avatar);
						@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
					}
					$oghtinrao->setHinh_anh($avatar);
					$model->save($oghtinrao);
					
					$msg = '<ul class="messages"><li class="success">Bạn đã đăng tin thành công và đang chờ duyệt.</li></ul>';
					$redirect = '<script type="text/javascript">
							        var settimmer = 0;
							        $(function(){
							                window.setInterval(function() {
							                    var timeCounter = $("b[id=show-time]").html();
							                    var updateTime = eval(timeCounter)- eval(1);
							                    $("b[id=show-time]").html(updateTime);
							
							                    if(updateTime == 0){
							                        window.location = ("' . $this->view->baseUrl('/member/oghtinrao/loaitin/' . $formData['loai_tin']) .'");
							                    }
							                }, 1000);
							
							        });
							    </script>';
					$redirect .= '<div class="redirect-msg"><div id="my-timer">Trang sẽ tự chuyển sau <b id="show-time">5</b> giây.</div><br />';
					$redirect .= '<p>Nếu không muốn đợt lâu vui lòng click vào <a href="' . $this->view->baseUrl('/member/oghinrao/loaitin/' . $formData['loai_tin']) .'">đây</a>.</p></div>';
					$this->view->msg = $msg;
					$this->view->redirect = $redirect;
					$this->renderScript('message/index.phtml');
				} else {
					$modelDistricts = new Default_Model_QuanHuyenMapper();
					$arrOptions = $modelDistricts->fetchAll('thanhpho = ' . $formData['thanh_pho']);
					$key = '';
					$value = ' -- Quận huyện -- ';
					foreach($arrOptions as $val) {
						$form->quan_huyen->addMultiOption($key, $value);
						$key   = $val->id;
						$value = $val->ten;
					}
					$form->quan_huyen->addMultiOption($key, $value);
					$form->populate($formData);
				}
			}
		}

	}

	// Chỉnh sửa tin ở ghép
	public function chinhsuatinoghepAction() {
		// Title
		$this->view->headTitle('Chỉnh sửa tin ở ghép');
		
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );

		$form = new Default_Form_OghTinRao();
		$form->submit->setLabel('Chỉnh sửa');
		$form->reset->setLabel('Hủy');
		$this->view->frmOghTinRao = $form;

		// Selectbox thành phố
		$model = new Default_Model_ThanhPhoMapper();
		$arrOptions = $model->fetchAll();
		$key = '';
		$value = ' -- Thành phố -- ';
		$form->thanh_pho->addMultiOption($key, $value);
		foreach($arrOptions as $val) {
			$key   = $val->id;
			$value = $val->ten;
			$form->thanh_pho->addMultiOption($key, $value);
		}
		$form->thanh_pho->setAttrib('onchange', 'getDistrict(false, thanh_pho, quan_huyen)');

		// Selectbox loại phòng
		$model = new Default_Model_LoaiPhongMapper();
		$arrOptions = $model->fetchAll('da_xoa = 0');
		$key = '';
		$value = ' -- Loại phòng -- ';
		$form->loai_phong->addMultiOption($key, $value);
		foreach($arrOptions as $val) {
			$key   = $val->id;
			$value = $val->ten;
			$form->loai_phong->addMultiOption($key, $value);
		}

		// Selectbox loại tin
		$model = new Default_Model_LoaiTinMapper();
		$arrOptions = $model->fetchAll('da_xoa = 0 AND group_loai_tin = 1');
		$key = '';
		$value = ' -- Loại tin -- ';
		foreach($arrOptions as $val) {
			$form->loai_tin->addMultiOption($key, $value);
			$key   = $val->id;
			$value = $val->ten;
		}
		$form->loai_tin->addMultiOption($key, $value);
		$model = new Default_Model_OghTinRaoMapper();
		$oghtinrao = $model->fetch($this->_arrParam, 'id = ' . $this->_arrParam['id']);

		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if (isset($formData['reset'])) {
				$this->_redirect('/member/oghtinrao/loaitin/' . $formData['loai_tin']);
			} elseif ($form->isValid($formData)) {
				$hinh_anh = $oghtinrao->hinh_anh;
				$data = new Default_Model_TableColumn_OghTinRao($formData);
				$data->setId($oghtinrao->id);
				$avatar = $formData['hidden_hinh_anh'];
				if ($avatar != $hinh_anh) {
					if ($avatar == "")
						$avatar = 'avatar_home.png';
					else {
						$uploadDir = $this->_controllerConfig['imagesDir'];
						$source = 'public/resources/tmp/thumb_images_64x64/';
						$destination = 'public/resources/phong_tro/avatar/';
						if ($avatar != 'avatar_home.png')
							@unlink($uploadDir . '/phong_tro/avatar/' . $avatar);
						copy($source . $avatar, $destination . $avatar);
						@unlink($uploadDir . '/tmp/full_images/' . $avatar);
						@unlink($uploadDir . '/tmp/thumb_images_64x64/' . $avatar);
					}
				}
				$data->setHinh_anh($avatar);
				$model->save($data);

				$this->_redirect('/member/oghtinrao/loaitin/' . $formData['loai_tin']);
			} else {
				$idThanhPho = $formData['thanh_pho'];
				$form->populate($formData);
			}
		} else {
			$idThanhPho = $oghtinrao->thanh_pho;
			$form->populate($oghtinrao->toArray());
		}
		
		$modelDistricts = new Default_Model_QuanHuyenMapper();
		$arrOptions = $modelDistricts->fetchAll('thanhpho = ' . $idThanhPho);
		$key = '';
		$value = ' -- Quận huyện -- ';
		foreach($arrOptions as $val) {
			$form->quan_huyen->addMultiOption($key, $value);
			$key   = $val->id;
			$value = $val->ten;
		}
		$form->quan_huyen->addMultiOption($key, $value);
		
	}

	// Danh sách tin rao phòng trọ
	public function oghtinraoAction() {
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );

		$loai_tin = 4;

		if (isset($this->_arrParam['loaitin'])) {
			$loai_tin = $this->_arrParam['loaitin'];
		}

		switch ($loai_tin) {
			case 3:
				$title = "Danh sách tin cần ở ghép";
				break;
					
			default:
				$title = "Danh sách tin tìm người ở ghép";
				break;
		}
		// Title
		$this->view->headTitle($title);

		$this->view->loaitin = $loai_tin;
		$this->view->title = $title;

		// Get items tin của table Ogh_Tin_Rao
		$model = new Default_Model_OghTinRaoMapper();
		$items = $model->fetch($this->_arrParam, 'nguoi_dang = ' . $this->_crrUsra->id . ' AND trang_thai <> 4 AND loai_tin = ' . $loai_tin, 0, array(array('colName' => 'ngay_dang', 'order' => 'DESC')), 'list');

		// Đếm số item trong Ogh_Tin_Rao
		$totalItem = $model->countItem($this->_arrParam, 'nguoi_dang = ' . $this->_crrUsra->id . ' AND trang_thai <> 2 AND loai_tin = ' . $loai_tin);
		$this->view->totalItems = $totalItem;

		$paginator = new Zendhlt_Paginator();
		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);

		$this->view->Items = $items;
		
		$form = new Default_Form_BuyVIP();
		$model = new Default_Model_GoiTinMapper();
		$arrOptions = $model->fetchAll('ten <> "free"', 'list');
		$key = 0;
		$value = ' -- Chọn gói VIP -- ';
		$form->ten_goi->addMultiOption($key, $value);
		foreach($arrOptions as $val) {
			$key   = $val['id'];
			$value = $val['ten'];
			$form->ten_goi->addMultiOption($key, $value);
		}
		$this->view->frmVIP = $form;
	}
	
	// Hộp thư
	public function hopthuAction() {
		// Title
		$this->view->headTitle('Thư đến');
		
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );
		$model = new Default_Model_TinNhanMapper();
		
		$loaithu = 'nguoi_nhan';
		$title = "Thư đến";
		$from = "Nguời gửi";
		$txtLoaiThu = "thuden";
		if (isset($this->_arrParam['loaithu']) && $this->_arrParam['loaithu'] == 'thudagui') {
			$loaithu = 'nguoi_gui';
			$title = "Thư đã gửi";
			$subject = "Nguời nhận";
			$txtLoaiThu = "thudagui";
		}
		
		if (isset($this->_arrParam['delete'])) {
			if (isset($this->_arrParam['cid'])) {
				$id = implode(',', $this->_arrParam['cid']);
			} else {
				$id = $this->_arrParam['delete'];
			}
			$model->delete($id);

			$this->_redirect('/member/hopthu/loaithu/' . $txtLoaiThu);
			return;
		}
		
		if (isset($this->_arrParam['view'])) {
			$item = $model->fetch($this->_arrParam, 'id = ' . $this->_arrParam['view'] . ' AND ' . $loaithu . ' = ' . $this->_crrUsra->id, 0);
			$this->view->item = $item;
		
			$form = new Default_Form_SendMail();
			$loaitin = 'ptrtinrao';
			$idtin = $item->ptr_tin_rao;
			if (empty($idtin)) {
				$loaitin = 'oghtinrao';
				$idtin = $item->ogh_tin_rao;
			}
			$form->id_bai_dang->setValue($idtin);
			$form->loai_bai_dang->setValue($loaitin);
			$form->id->setValue($this->_arrParam['view']);
			if ($item->nguoi_gui != 0) {
				$form->id_nguoi_dang->setValue($item->nguoi_gui);
				$form->email_nguoi_dang->setValue($item->getNguoiGuiObj()->email);
			}
			$form->nguoi_gui->setValue($this->_crrUsra->ho_ten)->setAttrib('readonly', 'true');
			$form->email_nguoi_gui->setValue($item->getNguoiNhanObj()->email)->setAttrib('readonly', 'true');
			$form->subject->setValue($item->tieu_de)->setAttrib('readonly', 'true');
			$this->view->form_sendmailtoposter = $form;
			if ($item->da_xem == 0)
				$model->change($this->_arrParam['view'], array('da_xem' => true));
			$this->renderScript('member/viewtinnhan.phtml');
			return;
		}
		$this->view->title = $title;
		$this->view->from = $from;
		$this->view->loaithu = $txtLoaiThu;
		
		$items = $model->fetch($this->_arrParam, $loaithu . ' = ' . $this->_crrUsra->id, 0, array(array('colName' => 'ngay_gui', 'order' => 'DESC')), 'list');
		$this->view->items = $items;
		
		// Đếm số item trong tb_tin_nhan
		$totalItem = $model->countItem($loaithu . ' = ' . $this->_crrUsra->id);
		$this->view->totalItem = $totalItem;
		
		$paginator = new Zendhlt_Paginator();
		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);
		
	}
	
	// Tài khoản
	public function taikhoanAction() {
		// Title
		$this->view->headTitle('Tài khoản chính');
		
		$layoutPath = TEMPLATE_PATH  . '/default';
		$option = array ('layout' => 'profile',
				'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );
		
		$model = new Default_Model_UsersMapper();
		$profile = $model->fetch('id = ' . $this->_crrUsra->id);
		$this->view->tai_khoan = $profile;
		
		$model = new Default_Model_GiaoDichMapper();
		$giaodich = $model->fetch($this->_arrParam, 'nguoi_dung = ' . $this->_crrUsra->id, 0, array(array('colName' => 'ngay_thuc_hien', 'order' => 'DESC')), 'list');
		$this->view->Items = $giaodich;
		
		// Đếm số item trong Giao dich
		$totalItem = $model->countItem($this->_arrParam, 'nguoi_dung = ' . $this->_crrUsra->id);
		$this->view->totalItems = $totalItem;

		$paginator = new Zendhlt_Paginator();
		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);
	}

	public function deleteAction() {
		$action = $this->_arrParam['actionpage'];
		$loai_tin = $this->_arrParam['loaitin'];
		if (isset($this->_arrParam['cid'])) {
			$id = implode(',', $this->_arrParam['cid']);
		} else {
			$id = $this->_arrParam['id'];
		}

		if ($action == 1) {
			$action = 'ptrtinrao';
			$key = 'ptr_tin_rao';
			$model = new Default_Model_PtrTinRaoMapper();
		} else {
			$action = 'oghtinrao';
			$key = 'ogh_tin_rao';
			$model = new Default_Model_OghTinRaoMapper();
		}
		$model->delete($id);
		$model = new Admin_Model_TinNhanMapper();
		$model->delete($id, $key);

		$this->_redirect('/member/' . $action . '/loaitin/' . $loai_tin);
	}

	// Validate form user
	public function validateformuserAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();

		$f = new Default_Form_User();
		//Remove các trường không được phép sửa;
		$f->removeElement('username');
		$f->removeElement('password');
		$f->removeElement('email');
		$f->isValid($this->_getAllParams());
		$json = $f->getMessages();
		header('Content-type: application/json');
		echo Zend_Json::encode($json);
	}

	// Validate form change password
	public function validateformchangepassAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();

		$f = new Default_Form_ChangePassword();
		$f->isValid($this->_getAllParams());
		$json = $f->getMessages();
		header('Content-type: application/json');
		echo Zend_Json::encode($json);
	}

	// Validate form đăng tin nhà trọ
	public function validateformptrtinraoAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();

		$f = new Default_Form_PtrTinRao();
		$f->isValid($this->_getAllParams());
		$json = $f->getMessages();
		header('Content-type: application/json');
		echo Zend_Json::encode($json);
	}

	// Validate form đăng tin ở ghép
	public function validateformoghtinraoAction() {
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->getHelper('layout')->disableLayout();

		$f = new Default_Form_OghTinRao();
		$f->isValid($this->_getAllParams());
		$json = $f->getMessages();
		header('Content-type: application/json');
		echo Zend_Json::encode($json);
	}

	// Upload slideshow hình ảnh và resize ảnh
	public function uploadifyAction() {
		if (!empty($_FILES)) {
			$uploadDir 	= $this->_controllerConfig['imagesDir'];
			$upload 	= new Zendhlt_File_Upload();
			$fnimage 	= $upload->upload('Filedata', $uploadDir . 'tmp/full_images/', array('task' => 'rename'));
			$linkImage = $uploadDir . 'tmp/full_images/' . $fnimage;
			$upload->resizeImage($fnimage, $linkImage, $uploadDir . 'tmp/thumb_images_428x320/', 428, 320);
			$upload->resizeImage($fnimage, $linkImage, $uploadDir . 'tmp/thumb_images_90x70/', 90, 70);
			echo $fnimage;
		}
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
	}

	// Upload hình ảnh avatar và resize ảnh
	public function uploadavatarAction() {
		if (!empty($_FILES)) {
			$uploadDir 	= $this->_controllerConfig['imagesDir'];
			$upload 	= new Zendhlt_File_Upload();
			$fnimage 	= $upload->upload('Filedata', $uploadDir . 'tmp/full_images/', array('task' => 'rename'));
			$linkImage = $uploadDir . 'tmp/full_images/' . $fnimage;
			$upload->resizeImage($fnimage, $linkImage, $uploadDir . 'tmp/thumb_images_64x64/', 64, 64);
			echo $fnimage;
		}
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
	}

	// Xóa ảnh trong folder tmp
	public function deleteimageAction() {
		// Không hiển thị layout lên
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();

		if (isset($_POST)) {
			$imgUrl = $this->_arrParam['imgUrl'];
			$filename = $this->_arrParam['filename'];
			$uploadDir 	= $this->_controllerConfig['imagesDir'];
			@unlink($uploadDir . '/tmp/full_images/' . $filename);
			@unlink($uploadDir . '/tmp/' . $imgUrl . '/' . $filename);
		} else {
			echo "wrong check";
		}
	}

	public function refreshAction() {
		$mask = APPLICATION_PATH."/../public/captcha/*.png";
		array_map("unlink", glob($mask));

		$form = new Default_Form_Contact();
		$captcha = $form->getElement('captcha')->getCaptcha();

		$data = array();

		$data['id']  = $captcha->generate();
		$data['src'] = $captcha->getImgUrl() .
		$captcha->getId() .
		$captcha->getSuffix();

		$this->_helper->json($data);
	}
	
	public function filterAction() {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if($this->_arrParam['type'] == 'search') {
			if($this->_arrParam['key'] == 1){
				$ssFilter->keywords = trim($this->_arrParam['keywords']);
			} else {
				$ssFilter->keywords = '';
			}
		}

		if($this->_arrParam['type'] == 'group') {
			$ssFilter->group_id = $this->_arrParam['group_id'];
		}

		if($this->_arrParam['type'] == 'order') {
			$ssFilter->col = $this->_arrParam['col'];
			$ssFilter->order = $this->_arrParam['by'];
		}

		$url = 'member/' . $ssFilter->actionname;
		if (isset($this->_arrParam['loaitin'])) {
			$url .= '/loaitin/' . $this->_arrParam['loaitin'];
		}
		$this->_redirect($url);
		$this->_helper->viewRenderer->setNoRender();
	}
	
	public function buyvipAction() {
		// Không hiển thị layout lên
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			$model = new Default_Model_GoiTinMapper();
			$items = $model->fetchAll('id = ' . $formData['ten_goi']);
			foreach ($items as $goi_tin) {
				$item = $goi_tin;
			}
			$model = new Default_Model_UsersMapper();
			$user = $model->fetch('id = ' . $this->_crrUsra->id);
			$flag = false;
			$total = $user->getTai_khoan_khuyen_mai() + $user->getTai_khoan_chinh();
			if ($total >= $item->gia_tien) {
				if ($user->getTai_khoan_khuyen_mai() >= $item->gia_tien) {
					$total = $user->getTai_khoan_khuyen_mai() - $item->gia_tien;
					$data = array('tai_khoan_khuyen_mai' => $total);
				} else {
					$total -= $item->gia_tien;
					$data = array('tai_khoan_khuyen_mai' => 0, 'tai_khoan_chinh' => $total);
				}
				$flag = true;
				$message = 'Up lên gói tin VIP thành công';
				$model->change($this->_crrUsra->id, $data);
				$model = new Default_Model_PtrTinRaoMapper();
				$tinrao = 'ptrtinrao';
				if (isset($this->_arrParam['loai']) && $this->_arrParam['loai'] == 2) {
					$model = new Default_Model_OghTinRaoMapper();
					$tinrao = 'oghtinrao';
				}
				$date_format = Default_Model_TableColumn_Users::DATE_FORMAT_FULL_EN;
				$now = date($date_format, time());
				$new_date = date($date_format, time() + 24 * 3600 * $item->so_ngay);
				$data = array('goi_tin' => $formData['ten_goi'], 'ngay_bat_dau' => $now, 'ngay_het_han' => $new_date);
				$model->change($formData['idtin'], $data);
				
				$giaodich = new Default_Model_TableColumn_GiaoDich();
				$giaodich->setGoi_tin($formData['ten_goi']);
				$giaodich->setNguoi_dung($this->_crrUsra->id);
				$giaodich->setUrl_tin($tinrao . '/view/id/' . $formData['idtin']);
				$model = new Default_Model_GiaoDichMapper();
				$model->save($giaodich);
			} else {
				$message = 'Số tiền trong tài khoản không đủ thực hiện thao tác này.';
			}
		}
		header('Content-type: application/json');
		$json = array('edit' => $flag, 'message' => $message);
		echo json_encode($json);
	}
}